package com.zyw.codegen.java;

import com.zyw.codegen.GeneratorContextHolder;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.config.PropertyRegistry;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

/**
 * @author zhangyw
 * @date 2017/3/15 11:07
 */
public class MVCGeneratorPlugin extends PluginAdapter {

    private MVCGenerator mvcGenerator;

    private String targetProject;
    private String rootClass;

    public MVCGeneratorPlugin(MVCGenerator mvcGenerator) {
        this.mvcGenerator = mvcGenerator;

    }

    @Override
    public boolean validate(List<String> warnings) {
        boolean f = true;
        String contextId = context.getId();
        if (!stringHasValue(targetProject)) {
            warnings.add(getString("ValidationError.2", contextId)); //$NON-NLS-1$
            f = false;
        }

        return f;
    }

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
        targetProject = properties.getProperty("targetProject");
        rootClass = properties.getProperty("rootClass");

        this.mvcGenerator.setContext(context);
        this.mvcGenerator.setProgressCallback(GeneratorContextHolder.getProgressCallback());
        this.mvcGenerator.setRootClass(rootClass);
    }

    @Override
    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
        this.mvcGenerator.setIntrospectedTable(introspectedTable);

        List<GeneratedJavaFile> answer = new ArrayList<GeneratedJavaFile>();

        List<CompilationUnit> compilationUnits = mvcGenerator.getCompilationUnits();
        for (CompilationUnit compilationUnit : compilationUnits) {
            GeneratedJavaFile gjf = new GeneratedJavaFile(compilationUnit, targetProject,
                    context.getProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING),
                    context.getJavaFormatter());
            answer.add(gjf);
        }

        return answer;
    }

    @Override
    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles() {
        return null;
    }
}
